package com.dennytech.tac.base;

import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.dennytech.tac.R;

public abstract class BasicAdapter extends BaseAdapter {
	public static final Object LOADING = new Object();
	public static final Object ERROR = new Object();
	public static final Object HEAD = new Object();
	public static final Object EMPTY = new Object();
	public static final Object LAST_EXTRA = new Object();

	protected View getLoadingView(ViewGroup parent, View convertView) {
		View v = convertView == null ? null
				: convertView.getTag() == LOADING ? convertView : null;
		if (v == null) {
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			v = inflater.inflate(R.layout.loading_item, parent, false);
			v.setTag(LOADING);
		}
		return v;
	}

	protected View getFailedView(String msg, View.OnClickListener retry,
			ViewGroup parent, View convertView) {
		View v = convertView == null ? null
				: convertView.getTag() == ERROR ? convertView : null;
		if (v == null) {
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			v = inflater.inflate(R.layout.error_item, parent, false);
			v.setTag(ERROR);
		}
		((TextView) v.findViewById(android.R.id.text1)).setText(msg);
		View rv = v.findViewById(R.id.btn_retry);
		rv.setVisibility(retry == null ? View.GONE : View.VISIBLE);
		rv.setOnClickListener(retry);
		rv.requestFocus();
		return v;
	}

	protected TextView getEmptyView(String emptyMsg, String defMsg,
			ViewGroup parent, View convertView) {

		TextView emptyTV = convertView == null ? null
				: convertView.getTag() == EMPTY ? (TextView)convertView : null;
		if (emptyTV == null) {
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			emptyTV = (TextView) inflater.inflate( R.layout.simple_list_item_18,
				parent, false);
			emptyTV.setTag(ERROR);

			Drawable d = parent.getResources().getDrawable(R.drawable.speaker);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			emptyTV.setCompoundDrawablePadding(8);
			emptyTV.setCompoundDrawables(d, null, null, null);

			emptyTV.setMovementMethod(LinkMovementMethod.getInstance());
		}

		if (TextUtils.isEmpty(emptyMsg)) {
			if (!TextUtils.isEmpty(defMsg)) {
			    emptyTV.setText(Html.fromHtml(defMsg));
			}
		} else {
			emptyTV.setText(Html.fromHtml(emptyMsg));
		}

		return emptyTV;
	}
}
